#include <stdio.h>
#include <string.h>
#include "gpio.h"


int gpio_export(unsigned char gpio_pin_number)
{
	FILE *fp;

	fp = fopen(SYS_GPIO_DIR "/export", "w");
	if (fp == NULL) {
		return FAILED;
	}

	fprintf(fp, "%hhu", gpio_pin_number);

	fclose(fp);

	return SUCCESS;
}

int gpio_unexport(unsigned char gpio_pin_number)
{
	FILE *fp;

	fp = fopen(SYS_GPIO_DIR "/unexport", "w");
	if (fp == NULL) {
		return FAILED;
	}

	fprintf(fp, "%hhu", gpio_pin_number);

	fclose(fp);

	return SUCCESS;
}

int gpio_set_direction(unsigned char gpio_pin_number, PIN_DIRECTION pin_direction)
{
	FILE *fp;
	char buf[MAX_BUF_LEN];

	memset(buf, 0, sizeof(buf));
	sprintf(buf, SYS_GPIO_DIR "/gpio%hhu/direction", gpio_pin_number);

	fp = fopen(buf, "w");
	if (fp == NULL) {
      printf("fopen error\n");
		return FAILED;
	}

	if(pin_direction == DIRECTION_INPUT)
		fprintf(fp, "in");
	else
		fprintf(fp, "out");

	fclose(fp);

	return SUCCESS;
}


int gpio_set_it_edge(unsigned char gpio_pin_number, PIN_IT_EDGE pin_edge)
{
	FILE *fp;
	char buf[MAX_BUF_LEN];

	memset(buf, 0, sizeof(buf));
	sprintf(buf, SYS_GPIO_DIR "/gpio%hhu/edge", gpio_pin_number);

	fp = fopen(buf, "w");
	if (fp == NULL) {
      printf("fopen error\n");
		return FAILED;
	}
    switch(pin_edge){
        case IT_NONE:
            fprintf(fp, "none");
            break;
        case IT_RISING:
            fprintf(fp, "rising");
            break;
        case IT_FALLING:
            fprintf(fp, "falling");
            break;
        case IT_RISING_FALLING:
            fprintf(fp, "both");
            break;    
        default:
            fprintf(fp, "none");
            break;
    }

	fclose(fp);

	return SUCCESS;
}



int gpio_set_value(unsigned char gpio_pin_number, PIN_VALUE pin_value)
{
	FILE *fp;
	char buf[MAX_BUF_LEN];

	memset(buf, 0, sizeof(buf));
	sprintf(buf, SYS_GPIO_DIR "/gpio%hhu/value", gpio_pin_number);

	fp = fopen(buf, "w");
	if (fp == NULL) {
		return FAILED;
	}

	if(pin_value == VALUE_LOW)
		fprintf(fp, "0");
	else
		fprintf(fp, "1");

	fclose(fp);

	return SUCCESS;

}


int gpio_get_value(unsigned char gpio_pin_number, uint32_t  *pin_value)
{
	FILE *fp;
	char buf[MAX_BUF_LEN];
	
	if(pin_value == NULL){
		return FAILED;
	}
	memset(buf, 0, sizeof(buf));
	sprintf(buf, SYS_GPIO_DIR "/gpio%hhu/value", gpio_pin_number);

	fp = fopen(buf, "r");
	if (fp == NULL) {
		return FAILED;
	}
	
	fscanf(fp, "%d", pin_value);
	fclose(fp);

	return SUCCESS;

}








